package service

import (
	"sync"

	"gitee.com/night-tc/gobige/global"
	"gitee.com/night-tc/gobige/logger"
	"gitee.com/night-tc/gobige/msgdef"
	"gitee.com/night-tc/gobige/msgdef/protomsg"
	"gitee.com/night-tc/gobige/threads"
	"github.com/shirou/gopsutil/cpu"
	"github.com/shirou/gopsutil/mem"
)

/*
服务器还需要主动链接别的服务器需要管理
*/

/* IsrvInst 接口 */

// 操作子协程的管理器
func (this *Service) GetThreadGo() *threads.ThreadGo {
	return this.thgo
}

// 获取服务器当前繁忙状态0-100
func (this *Service) GetLoad() int {
	var c int
	var vm int

	if loads, err := cpu.Percent(0, false); err == nil {
		if len(loads) > 0 {
			c = int(loads[0])
		}
	} else {
		logger.Error(err)
		c = 100
	}

	if memorys, err := mem.VirtualMemory(); err == nil {
		vm = int(memorys.UsedPercent)
	} else {
		logger.Error(err)
		vm = 100
	}

	if c > vm {
		return c
	}

	return vm
}

// 发消息给其他服务器的对象
func (this *Service) PostMsgToEntity(srvid, spid, eid uint64, msg msgdef.IMsg) (err error) {
	if srvmsg, err := this.packSrvMsg(global.ServerTypeDefault, srvid, spid, eid, msg); err != nil {
		return err
	} else {
		this.PostSess(srvid, srvmsg)
		return nil
	}
}

// 发这消息到目标服务器
func (this *Service) PostSess(srvid uint64, msg msgdef.IMsg) {
	if global.GetCfgInst().GetServerID() == srvid {
		this.FireMsg(msg.Name(), msg)
	} else if nsess := this.GetClientSess(srvid); nsess != nil {
		nsess.Send(msg)
	}
}

// 通过目标服务器发消息给客户端
func (this *Service) PostMsgToClient(srvid, spid, eid uint64, msg msgdef.IMsg) (err error) {
	if srvmsg, err := this.packSrvMsg(global.ServerTypeClient, srvid, spid, eid, msg); err != nil {
		return err
	} else {
		this.PostSess(srvid, srvmsg)
		return nil
	}
}

// 通过目标服务器发消息给客户端
func (this *Service) PostMsgToClientBuf(srvid, spid, eid uint64, data []byte) (err error) {
	if srvmsg, err := this.packBufSrvMsg(global.ServerTypeClient, srvid, spid, eid, data); err != nil {
		return err
	} else {
		this.PostSess(srvid, srvmsg)
		return nil
	}
}

////////////////////////////////////////////////////////////
/* 属性 */

// IsSrvValid 服务是否可用
func (this *Service) IsSrvValid() bool {
	return protomsg.ServerStatus(this.Status.Load()) == protomsg.ServerStatus_DefaultOK
}

// // HandlerSrvInvalid 处理服务不可用
// func (this *Service) HandlerSrvInvalid(entityID uint64) {
// 	e := this.GetEntity(entityID)
// 	if e.GetType() == common.EntityType_Player {

// 		logger.Warn("服务器把你炸下线了 ", e)

// 		_ = this.DestroyEntity(entityID)
// 	}
// }

// 获取新的EntityID
func (this *Service) GetNewEID() uint64 {
	return this.eIDGenerater.GenerateID()
}

// 获取等待回复的map
func (this *Service) GetWaitMap() *sync.Map {
	return &this.WaitList
}

/* 属性 */
////////////////////////////////////////////////////////////
